package com.example.designer.singleton;

/**
 * @author zhaoyunlong
 * @date 2020/12/16
 * @description
 * 懒汉模式  lazy loading
 *    虽然达到了按需初始化的目的，但是却线程不安全
 *    可以添加synchronized来解决   但是效率不高
 */
public class SingletonThree {

    public static SingletonThree instance;

    private SingletonThree(){

    }

    public static synchronized SingletonThree getInstance(){
        if (instance == null) {
            try {
                Thread.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = new SingletonThree();
        }
        return instance;
    }

    public static void main(String[] args) {

        for (int i=0; i < 100; i++) {
            new Thread(()->{
                //不同对象的 hashcode是不一样的
                SingletonThree singleton2 = SingletonThree.getInstance();
                System.out.println(singleton2.hashCode());
            }).start();
        }
    }
}
